package com.opennews.openplatform.security

import com.opennews.openplatform.DateHelper
import com.opennews.openplatform.UserActiveToken

class UserActiveTokenManager {
    // It only caches access tokens since refresh tokens never expire.
    // By using cached access tokens would reduce access to database.
    private static List<UserActiveToken> cachedUserActiveTokens;

    /**
     * Checks if this access token is still active. If the data does not exist means the token has been revoked.
     * @param username : The string of username.
     * @param accessToken : The string of access token.
     * @return True means the token is active. False means not active.
     */
    boolean isActiveAccessToken(String username, String accessToken) {
        return getCachedUserActiveTokens().find {
            it.username == username &&
                it.accessToken == accessToken
        } != null
    }

    List<UserActiveToken> getCachedUserActiveTokens() {
        if (cachedUserActiveTokens == null) {
            reloadCachedUserActiveTokenRecords();
        }

        return cachedUserActiveTokens;
    }

    /**
     * Loads all enabled and valid access tokens.
     */
    void reloadCachedUserActiveTokenRecords() {
        cachedUserActiveTokens = UserActiveToken.where {
            dateExpired >= DateHelper.getCurrentDate() &&
                enabled
        }.list();
    }
}
